<template>
  <div class="dashboard">
    <!-- 页面头部 -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="greeting">
          <h1>欢迎回来，{{ userInfo.name }}</h1>
          <p>{{ currentDate }}</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="gotoReconciliation">
            <el-icon><MagicStick /></el-icon>
            智能对账
          </el-button>
          <el-button @click="refreshInsights">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button @click="showNotifications">
            <el-icon><Bell /></el-icon>
            提醒
            <el-badge 
              v-if="notifications.length > 0" 
              :value="notifications.length" 
              type="danger"
              class="notification-badge"
            />
          </el-button>
        </div>
      </div>
    </div>

    <!-- 关键指标 -->
    <el-row :gutter="20" class="metrics-section">
      <el-col :span="6">
        <MetricCard 
          title="待处理流水"
          :value="metrics.pendingTransactions"
          :trend="metrics.transactionTrend"
          :color="'#409eff'"
          icon="Document"
          @click="gotoPendingTransactions"
        />
      </el-col>
      <el-col :span="6">
        <MetricCard 
          title="待匹配订单"
          :value="metrics.pendingMatches"
          :trend="metrics.matchTrend"
          :color="'#67c23a'"
          icon="TrendCharts"
          @click="gotoPendingMatches"
        />
      </el-col>
      <el-col :span="6">
        <MetricCard 
          title="待处理订单"
          :value="metrics.pendingOrders"
          :trend="metrics.orderTrend"
          :color="'#e6a23c'"
          icon="SuccessFilled"
          @click="gotoPendingOrders"
        />
      </el-col>
      <el-col :span="6">
        <MetricCard 
          title="对账准确率"
          :value="metrics.accuracyRate"
          :trend="metrics.accuracyTrend"
          :color="'#f56c6c'"
          suffix="%"
          icon="Checked"
        />
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧：AI洞察和待办事项 -->
      <el-col :span="16">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-card class="ai-insights-card">
              <template #header>
                <div class="card-header">
                  <span><el-icon><MagicStick /></el-icon> AI智能洞察</span>
                  <el-button link @click="refreshInsights">
                    <el-icon><Refresh /></el-icon> 刷新
                  </el-button>
                </div>
              </template>
              <InsightList 
                :insights="aiInsights" 
                :loading="insightLoading"
                @refresh="refreshInsights"
              />
            </el-card>
          </el-col>
          <el-col :span="24">
            <el-card class="todo-card">
              <template #header>
                <div class="card-header">
                  <span><el-icon><Clock /></el-icon> 待办事项</span>
                  <div class="todo-header-actions">
                    <span class="pending-count">待处理: {{ pendingTasks }} 项</span>
                    <el-button link @click="gotoTodoList">
                      <el-icon><More /></el-icon> 查看全部
                    </el-button>
                  </div>
                </div>
              </template>
              <TodoList 
                :todos="quickTodos" 
                :loading="todoLoading"
                @todo-click="handleTodoClick"
                @todo-complete="handleTodoComplete"
              />
            </el-card>
          </el-col>
        </el-row>
      </el-col>

      <!-- 右侧：活动和通知 -->
      <el-col :span="8">
        <el-card class="activity-card">
          <template #header>
            <div class="card-header">
              <span><el-icon><Bell /></el-icon> 最近活动</span>
              <el-button link @click="showActivityHistory">
                <el-icon><More /></el-icon> 查看历史
              </el-button>
            </div>
          </template>
          <ActivityTimeline 
            :activities="recentActivities" 
            :loading="activityLoading"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 通知抽屉 -->
    <NotificationDrawer 
      v-model="notificationVisible"
      :notifications="notifications"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from '@vue/runtime-core'
import { useRouter } from 'vue-router'
// import { useUserStore } from '@/stores/user'
import { useDashboardStore } from '@/stores/dashboard'
import { 
  TrendCharts, Bell, Money, Checked, Document, SuccessFilled, 
  MagicStick, Refresh, More, Clock, CaretTop, CaretBottom, ArrowUp 
} from '@element-plus/icons-vue'

// 组件导入
import MetricCard from './components/MetricCard.vue'
import InsightList from './components/InsightList.vue'
import TodoList from './components/TodoList.vue'
import ActivityTimeline from './components/ActivityTimeline.vue'
import NotificationDrawer from './components/NotificationDrawer.vue'

// Store 和 Router
// const userStore = useUserStore()
const dashboardStore = useDashboardStore()
const router = useRouter()

// 模拟用户信息
const userInfo = ref({ name: '管理员' })

// 响应式数据
const trendPeriod = ref('30d')
const notificationVisible = ref(false)

const chartLoading = ref(false)
const insightLoading = ref(false)
const todoLoading = ref(false)
const activityLoading = ref(false)

// 数据
const metrics = reactive({
  pendingTransactions: 24,
  pendingMatches: 12,
  pendingOrders: 8,
  accuracyRate: 96.5,
  transactionTrend: 5.2,
  matchTrend: 3.8,
  orderTrend: -2.1,
  accuracyTrend: 1.5,
  highConfidenceMatches: 7,
  pendingAmount: 125000,
  totalCustomers: 42,
  monthlyAmount: 2850000,
  efficiencyScore: 88,
  customerTrend: 8.3,
  amountTrend: 12.7
})

const aiInsights = ref([])
const quickTodos = ref([])
const recentActivities = ref([])
const notifications = ref([])

// 计算属性
const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

const pendingTasks = computed(() => {
  return quickTodos.value.filter((todo: any) => !todo.completed).length
})

// 方法
const loadDashboardData = async () => {
  try {
    // 并行加载所有数据
    await Promise.all([
      loadMetrics(),
      loadInsights(),
      loadTodos(),
      loadActivities(),
      loadNotifications()
    ])
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
  }
}

const loadMetrics = async () => {
  // const data = await dashboardStore.getDashboardMetrics()
  // Object.assign(metrics, data)
}

const loadInsights = async () => {
  insightLoading.value = true
  try {
    // aiInsights.value = await dashboardStore.getAIInsights()
  } finally {
    insightLoading.value = false
  }
}

const loadTodos = async () => {
  todoLoading.value = true
  try {
    // quickTodos.value = await dashboardStore.getQuickTodos()
  } finally {
    todoLoading.value = false
  }
}

const loadActivities = async () => {
  activityLoading.value = true
  try {
    // recentActivities.value = await dashboardStore.getRecentActivities()
  } finally {
    activityLoading.value = false
  }
}

const loadNotifications = async () => {
  // notifications.value = await dashboardStore.getNotifications()
}

const refreshInsights = () => {
  loadInsights()
}

const gotoReconciliation = () => {
  router.push('/finance/reconciliation/workbench')
}

const gotoPendingTransactions = () => {
  router.push('/finance/reconciliation/workbench')
}

const gotoPendingMatches = () => {
  router.push('/reconciliation/results?status=pending')
}

const gotoPendingOrders = () => {
  router.push('/sales/orders')
}

const gotoTodoList = () => {
  router.push('/tasks')
}

const showNotifications = () => {
  notificationVisible.value = true
}

const showActivityHistory = () => {
  router.push('/activities')
}

const handleTodoClick = (todo: any) => {
  switch (todo.type) {
    case 'reconciliation':
      router.push('/finance/reconciliation/workbench')
      break
    case 'review':
      router.push('/reconciliation/results?status=pending')
      break
    default:
      break
  }
}

const handleTodoComplete = async (todo: any) => {
  try {
    // await dashboardStore.completeTodo(todo.id)
    // 重新加载待办列表
    loadTodos()
  } catch (error) {
    console.error('完成待办失败:', error)
  }
}

const formatCurrency = (amount: number) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 生命周期
onMounted(() => {
  loadDashboardData()
  
  // 设置自动刷新
  const refreshInterval = setInterval(() => {
    loadMetrics()
  }, 30000) // 每30秒刷新一次指标和提醒

  // 清理定时器
  // onUnmounted(() => {
  //   clearInterval(refreshInterval)
  // })
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.dashboard-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.greeting h1 {
  margin: 0 0 5px 0;
  font-size: 24px;
  font-weight: 600;
}

.greeting p {
  margin: 0;
  color: #666;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.notification-badge {
  margin-left: 5px;
}

.metrics-section {
  margin-bottom: 20px;
}

.main-content {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.todo-header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.pending-count {
  font-size: 12px;
  color: #666;
}

.ai-insights-card,
.todo-card,
.activity-card {
  height: 100%;
}

:deep(.el-card__body) {
  height: calc(100% - 50px);
}
</style>